<?php

namespace app\index\controller;

use app\commons\model\Member;
use app\commons\model\SaleCard;
use app\index\controller\Main;
use think\Controller;
use think\Db;
use QRcode;
use commonsdk\Tools;
use think\Exception;
use app\commons\model\Sale as SaleModel;
use think\exception\ValidateException;

class Sale extends Main {

    public function index(SaleModel $saleModel) {

        $_GPC = $this->data;
        $map = [];
        if (isset($_GPC['member_id']) && $_GPC['member_id'] != '') {
            $map['m.id'] = $_GPC['member_id'];
        } elseif ($this->merchinfo['isagent']) {
            if ($this->sysset['agent_level'] != '') {
                if ($this->sysset['agent_level'][$this->merchinfo['agent_level']]['type'] == 0) {
                    $map['m.agent_id'] = $this->merchinfo['id'];
                }
                if ($this->sysset['agent_level'][$this->merchinfo['agent_level']]['type'] == 1) {
                    $map['m.province'] = $this->merchinfo['province'];
                    $map['m.city'] = $this->merchinfo['city'];
                    $map['m.area'] = $this->merchinfo['area'];
                    $map['m.agent_id'] = $this->merchinfo['id'];
                }
                if ($this->sysset['agent_level'][$this->merchinfo['agent_level']]['type'] == 2) {
                    $map['m.province'] = $this->merchinfo['province'];
                    $map['m.city'] = $this->merchinfo['city'];
                    $map['m.agent_id'] = $this->merchinfo['id'];
                }
                if ($this->sysset['agent_level'][$this->merchinfo['agent_level']]['type'] == 3) {
                    $map['m.province'] = $this->merchinfo['province'];
                    $map['m.agent_id'] = $this->merchinfo['id'];
                }
            } else {
                $map['m.agent_id'] = $this->merchinfo['id'];
            }
        } else {
            $map['s.member_id'] = $this->merchinfo['id'];
        }
       
        if (isset($_GPC['paytype']) && $_GPC['paytype'] != '') {
            $map['s.paytype'] = $_GPC['paytype'];
        }
        if (isset($_GPC['status']) && $_GPC['status'] != '') {
            $map['s.status'] = $_GPC['status'];
        }
        $db = $saleModel
        ->alias('s')
        ->field('s.*')
        ->join("member m", 's.member_id=m.id')
        ->where($map);
         if (!empty($_GPC['title'])) {
            $db->whereLike('s.title','%' . $_GPC['title'] . '%');
        }
        $data = $db->paginate(10,false,['query'=>request()->param()]);
        return jsonp($data);
    }

    /**
     * 编辑活动
     */
    public function update(SaleModel $sale, \app\commons\model\ActivityVideo $activityVideo, SaleCard $saleCard){
        $validate = new \app\index\validate\Sale();
        if (!$validate->scene('edit')->check($this->data)) {
            throw new ValidateException($validate->getError());
        }
        //验证活动时间
        if(strtotime($this->data['starttime']) >= strtotime($this->data['endtime'])){
            throw new ValidateException('活动开始日期必须小于结束日期');
        }

        //验证商家扫码点数
        $member = Member::where(['id'=>$this->merchinfo['id']])->find();
        if(!$member || $member['ismerch'] != 1) throw new ValidateException('非法账号信息！');
        if($member['endtime'] > 0){
            if($member['endtime'] < time()) throw new ValidateException('账号已过期！');
        }

        if($member['num'] <= 0)  throw new ValidateException('商家点数不足！');
        $sale_num = SaleModel::where(array('member_id' => $this->merchinfo['id']))->count();
        if ($member['sale_num'] <= $sale_num) {
            throw new ValidateException('商家活动数量已满：' . $member['sale_num'] . '，不能添加新活动！');
        }
        //验证视频格式
        if(isset($this->data['video'])){
            if(!is_array($this->data['video'])) throw new ValidateException('视频数据格式错误！');
        }
        //验证卡券信息
        if($this->data['paytype'] == 0){
            if(!is_array($this->data['card'])) throw new ValidateException('卡券数据格式错误！');
        }

        Db::startTrans();
        try {
            $addData = $this->data;
            $addData['poster'] = json_encode($addData['poster']);
            $addData['card'] = json_encode($addData['card']);
            $addData['video'] = json_encode($addData['video']);
            $addData['replace'] = json_encode($addData['replace']);
            $addData['starttime'] = strtotime($addData['starttime']);
            $addData['endtime'] = strtotime($addData['endtime']);
            $addData['member_id'] = $this->merchinfo['id'];
            $res = $sale->allowField(true)->save($addData,['id'=>$addData['id']]);
            if(!$res) throw new Exception('编辑失败！');
            //处理添加的视频信息
            $videoAll = [];
            if(!empty($this->data['video'])){
                foreach ($this->data['video'] as $datum){
                    if(!isset($datum['id'])){
                        $videoAll[] = [
                            'path'=>$datum['path'],
                            'title'=>$datum['title'],
                            'sale_id'=>$addData['id'],
                            'status'=>'1',
                            'download_time'=>date('Y-m-d H:i:s'),
                            'synthesis_time'=>date('Y-m-d H:i:s'),
                        ];
                    }
                }
            }
            if(!empty($videoAll)){
                $activityVideoRes = $activityVideo->allowField(true)->saveAll($videoAll);
                if(!$activityVideoRes) throw new Exception('编辑视频数据失败！');
            }
            //处理卡券信息
            $cardAll = [];
            if(!empty($this->data['card'])){
                $cardAll = [
                    'sale_id'=>$addData['id'],
                    'card'=>$this->data['card']['desc'],
                    'cardidx'=>$this->data['template'],
                    'type'=>$this->data['card']['type'],//优惠券类型，0，无限制；1，满减
                    'term'=>$this->data['card']['term'],//有效天数
                    'starttime'=>$this->data['card']['starttime'],//开始时间（设置有效天数后无效）
                    'endtime'=>$this->data['card']['endtime'],//结束时间（设置有效天数后无效）
                    'title'=>$this->data['card']['title'],//优惠券名称
                    'price'=>$this->data['card']['price'],//优惠券金额
                    'full_money'=>$this->data['card']['full_money'],//满减券需要达到的金额
                    'user_limit'=>$this->data['card']['user_limit'],//每人限制领取数量
                    'num'=>$this->data['card']['num'],//卡券总数量
                    'user_id'=>$this->merchinfo['id'],//卡券总数量
                ];
            }
            if(!empty($cardAll)){
                $saleCardRes = $saleCard->allowField(true)->save($cardAll,['id'=>$this->data['card']['id']]);
                if(!$saleCardRes) throw new Exception('编辑卡券数据失败！');
            }
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            throw new ValidateException($exception->getMessage());
        }
        return jsonp([]);
    }

    /**
     * 创建活动
     */
    public function create(SaleModel $sale, \app\commons\model\ActivityVideo $activityVideo, SaleCard $saleCard){
        $validate = new \app\index\validate\Sale();
        if (!$validate->scene('add')->check($this->data)) {
            throw new ValidateException($validate->getError());
        }
        //验证活动时间
        if(strtotime($this->data['starttime']) >= strtotime($this->data['endtime'])){
            throw new ValidateException('活动开始日期必须小于结束日期');
        }

        //验证商家扫码点数
        $member = Member::where(['id'=>$this->merchinfo['id']])->find();
        if(!$member || $member['ismerch'] != 1) throw new ValidateException('非法账号信息！');
        if($member['endtime'] > 0){
            if($member['endtime'] < time()) throw new ValidateException('账号已过期！');
        }

        if($member['num'] <= 0)  throw new ValidateException('商家点数不足！');
        $sale_num = SaleModel::where(array('member_id' => $this->merchinfo['id']))->count();
        if ($member['sale_num'] <= $sale_num) {
            throw new ValidateException('商家活动数量已满：' . $member['sale_num'] . '，不能添加新活动！');
        }
        //验证视频格式
        if(isset($this->data['video'])){
            if(!is_array($this->data['video'])) throw new ValidateException('视频数据格式错误！');
        }
        //验证卡券信息
        if($this->data['paytype'] == 0){
            if(!is_array($this->data['card'])) throw new ValidateException('卡券数据格式错误！');
        }
        Db::startTrans();
        try {
            $addData = $this->data;
            $addData['poster'] = json_encode($addData['poster']);
            $addData['card'] = json_encode($addData['card']);
            $addData['video'] = json_encode($addData['video']);
            $addData['replace'] = json_encode($addData['replace']);
            $addData['starttime'] = strtotime($addData['starttime']);
            $addData['endtime'] = strtotime($addData['endtime']);
            $addData['member_id'] = $this->merchinfo['id'];
            $res = $sale->allowField(true)->save($addData);
            if(!$res) throw new Exception('创建失败！');
            //处理添加的视频信息
            $videoAll = [];
            if(!empty($this->data['video'])){
                foreach ($this->data['video'] as $datum){
                    $videoAll[] = [
                        'path'=>$datum['path'],
                        'title'=>$datum['title'],
                        'sale_id'=>$sale->id,
                        'status'=>'1',
                        'download_time'=>date('Y-m-d H:i:s'),
                        'synthesis_time'=>date('Y-m-d H:i:s'),
                    ];
                }
            }
            if(!empty($videoAll)){
                $activityVideoRes = $activityVideo->allowField(true)->saveAll($videoAll);
                if(!$activityVideoRes) throw new Exception('创建视频数据失败！');
            }
            //处理卡券信息
            $cardAll = [];
            if(!empty($this->data['card'])){
                    $cardAll = [
                        'sale_id'=>$sale->id,
                        'card'=>$this->data['card']['desc'],
                        'cardidx'=>$this->data['template'],
                        'type'=>$this->data['card']['type'],//优惠券类型，0，无限制；1，满减
                        'term'=>$this->data['card']['term'],//有效天数
                        'starttime'=>$this->data['card']['starttime'],//开始时间（设置有效天数后无效）
                        'endtime'=>$this->data['card']['endtime'],//结束时间（设置有效天数后无效）
                        'title'=>$this->data['card']['title'],//优惠券名称
                        'price'=>$this->data['card']['price'],//优惠券金额
                        'full_money'=>$this->data['card']['full_money'],//满减券需要达到的金额
                        'user_limit'=>$this->data['card']['user_limit'],//每人限制领取数量
                        'num'=>$this->data['card']['num'],//卡券总数量
                    ];
            }
            if(!empty($cardAll)){
                $saleCardRes = $saleCard->allowField(true)->save($cardAll);
                if(!$saleCardRes) throw new Exception('创建卡券数据失败！');
            }
            Db::commit();
        }catch (Exception $exception){
            Db::rollback();
            throw new ValidateException($exception->getMessage());
        }
        return jsonp([]);
    }

    /**
     * 结束活动
     */
    public function  closure(){
        $data = request()->param();
        $id = $data['id'] ?? 0;
        if(!$id) throw new ValidateException('参数错误！');
        $sale = \app\commons\model\Sale::where(['id'=>$id,'member_id'=>session('user')])->find();
        if(!$sale) throw new ValidateException('活动不存在！');
        if($sale['status'] == 1) throw new ValidateException('活动已结束！');
        $res = \app\commons\model\Sale::where(['id'=>$id,'member_id'=>session('user')])->update(['status'=>1]);
        if(!$res) throw new ValidateException('结束活动失败！');
        return jsonp([]);
    }

    public function add() {
        $validate = new \app\index\validate\Sale();
        if (!$validate->scene('add')->check($this->data)) {
            throw new ValidateException($validate->getError());
        }
        $_GPC['data'] = $this->data;
        if (request()->isPost()) {
            $token = check_formtoken();
            unset($_GPC['data']['token']);
            if (isset($_GPC['data']['member_id']) && $this->merchinfo['isagent'] == 1) {
                $user = pdo_get('member', array('id' => $_GPC['data']['member_id']));
                if (!$user || $user['agent_id'] != $this->merchinfo['id']) {
                    return jsonp_error(422,'商家ID填写错误！');
                }
            } else {
                $_GPC['data']['member_id'] = $this->merchinfo['id'];
            }
            $member = pdo_get('member', array('id' => $this->merchinfo['id']));
            if ($member['num'] != 0 && max($member['num'], 0) < $_GPC['data']['number']) {
                return jsonp_error(422,'商家点数剩余：' . max($member['num'], 0) . '，扫码次数最多只能填写：' . max($member['num'], 0) . '！');
//                json(array('token' => $token), 1, '商家点数剩余：' . max($member['num'], 0) . '，扫码次数最多只能填写：' . max($member['num'], 0) . '！');
            }
            if ($member['num'] != 0 && $_GPC['data']['number'] == 0) {
                return jsonp_error(422,'扫码次数必须大于0！');
//                json(array('token' => $token), 1, '扫码次数必须大于0！');
            }
            if ($member['sale_num'] != 0) {
                $sale_num = Db::name('sale')->where(array('member_id' => $_GPC['data']['member_id']))->count();
                if ($member['sale_num'] <= $sale_num) {
                    return jsonp_error(422,'商家活动数量已满：' . $member['sale_num'] . '，不能添加新活动！');
//                    json(array('token' => $token), 1, '商家活动数量已满：' . $member['sale_num'] . '，不能添加新活动！');
                }
            }
            $alivideo = true;
            $_GPC['data']['createtime'] = time();
            $_GPC['data']['starttime'] = strtotime($_GPC['data']['starttime']);
            $_GPC['data']['endtime'] = strtotime($_GPC['data']['endtime']);
            $_GPC['data']['poster'] = isset($_GPC['data']['poster'])?json_encode($_GPC['data']['poster']):"";
            $_GPC['data']['video'] = json_encode($_GPC['data']['video']);
            $_GPC['data']['replace'] = json_encode($_GPC['data']['replace']);
            $_GPC['data']['card'] = json_encode($_GPC['data']['card']);
            $result = pdo_insert('sale', $_GPC['data']);
            if (!empty($result) || $result === 0) {
                if ($member['num'] != 0) {
                    $member['num'] = $member['num'] + $data['number'] - $_GPC['data']['number'];
                    $member['num'] != 0 or $member['num'] = -1;
                    pdo_update('member', $member, array('id' => $member['id']));
                }
                if ($alivideo) {
                    $id = Db::name('sale')->getLastInsID();
                    asyn_http_get(request()->domain(true) . '/web/alivideo?sale_id=' . $id);
                }
                return jsonp(array('token' => $token));
            } else {
                return jsonp_error(422, '提交失败！');
            }
        }
        $data = array();
        $data['isagent'] = $this->merchinfo['isagent'];
        return jsonp($data);
    }

    public function edit() {

        $_GPC['data'] = $this->data;
        $id = $_GPC['data']['id'];
        try {
        $data = SaleModel::where('id',$id)->find();
        if (request()->isPut()) {
            $validate = new \app\index\validate\Sale();
            if (!$validate->scene('edit')->check($this->data)) {
                throw new ValidateException($validate->getError());
            }
            $token = check_formtoken();
            unset($_GPC['data']['token']);
            
            if (isset($_GPC['data']['member_id']) && $this->merchinfo['isagent'] == 1) {
                $user = pdo_get('member', array('id' => $_GPC['data']['member_id']));
                if (!$user || $user['agent_id'] != $this->merchinfo['id']) {
                    return jsonp_error(422, '商家ID填写错误！');
                }
            }
            $member = pdo_get('member', array('id' => $this->merchinfo['id']));
            if ($member['num'] != 0 && max($member['num'], 0) + $data['number'] < $_GPC['data']['number']) {
                return jsonp_error(422, '商家点数剩余：' . (max($member['num'], 0) + $data['number']) . '，扫码次数最多只能填写：' . (max($member['num'], 0) + $data['number']) . '！');
            }
            if ($member['num'] != 0 && $_GPC['data']['number'] == 0) {
                return jsonp_error(422, '扫码次数必须大于0！');
            }

                $alivideo =  true;
                $_GPC['data']['starttime'] = strtotime($_GPC['data']['starttime']);
                $_GPC['data']['endtime'] = strtotime($_GPC['data']['endtime']);
                $_GPC['data']['poster'] = json_encode($_GPC['data']['poster']);
                $_GPC['data']['video'] = json_encode($_GPC['data']['video']);
                $_GPC['data']['replace'] = json_encode($_GPC['data']['replace']);
                $_GPC['data']['card'] = json_encode($_GPC['data']['card']);
                $result = pdo_update('sale', $_GPC['data'], array('id' => $id));
                if (!empty($result) || $result === 0) {
                    if ($member['num'] != 0) {
                        $member['num'] = $member['num'] + $data['number'] - $_GPC['data']['number'];
                        $member['num'] != 0 or $member['num'] = -1;
                        pdo_update('member', $member, array('id' => $member['id']));
                    }
                    if ($alivideo) {
                        die;
                        asyn_http_get(request()->domain(true) . '/web/alivideo&sale_id=' . $id);
                    }
                    return jsonp(array('token' => $token));
                } else {
                    return jsonp_error(422, '提交失败！');
                }
        }
        $data['scope'] = explode(',', $data['scope']);
        $data['alivideourl'] = request()->domain(true) . '/web/alivideo?sale_id=' . $id;
        $data['isagent'] = $this->merchinfo['isagent'];
        }catch (Exception $exception){
            return jsonp_error(422, $exception->getMessage());
        }
        return jsonp($data);
    }

    public function del() {

        $_GPC = input();
        $id = $_GPC['id'];
        if ($this->request->isPost()) {
            $result =Db::name('sale')->whereIn('id',$id)->delete();
            if (!empty($result) || $result === 0) {
                json('success', 0, '删除成功');
            } else {
                json('error', 1, '删除失败');
            }
        }
        return json('', 1, 'error');
    }

    public function aliaddvideo() {

        $_GPC = input();
        $data = array();
        jsont(get_upload_data($data));
    }

    public function endsale() {

        $_GPC = $this->data;
        $id = $_GPC['id'];
        if (request()->isPost()) {
            $result = $result = pdo_update('sale', array('endtime' => time() - 86401), array('id' => $id));
            if (!empty($result) || $result === 0) {
                return jsonp([]);
            } else {
                return jsonp_error(422, '操作失败');
            }
        }
        return jsonp_error(422, 'error');
    }

    public function verifyer() {

        $_GPC = $this->data;
        $page = max(intval($_GPC['page']), 1);
        $limit = max(intval($_GPC['limit']), 1);

        $row = Db::name('sale_verifyer')->alias('v')
                ->join('member m', 'v.member_id=m.id')
                ->field('v.*,m.avatar,m.nickname')
                ->where(array('v.sale_id' => $_GPC['id']));
        $data = $row->paginate($page);
        return jsonp($data);
    }

    public function addverifyer() {

        $_GPC = input();
        $result = pdo_insert('sale_verifyer', array('member_id' => $_GPC['member_id'], 'sale_id' => $_GPC['id'], 'createtime' => time()));
        if (!empty($result) || $result === 0) {
            return jsonp([]);
        } else {
            return json(422, '提交失败！');
        }
    }

    public function delverifyer() {

        $_GPC = input();
        $id = $_GPC['id'];
        if ($this->request->isPost()) {
            $result = pdo_query("DELETE FROM " . tablename('sale_verifyer') . " WHERE id in ($id)");
            if (!empty($result) || $result === 0) {
                json('删除成功');
            } else {
                  json('', 1, '删除失败');
            }
        }
        json('', 1, 'error');
    }

    public function verifyerqr() {

        $_GPC = $this->data;
        return jsonp(['url'=>request()->domain(true) . '/web/index/bindverifyer?id=' . $_GPC['id']]);
        header('content-type: image/png');
        require_once '../extend/qrcode/phpqrcode.php';
        ob_start();
        QRcode::png(request()->domain(true) . '/web/index/bindverifyer?id=' . $_GPC['id'], false, 'L', 5, 2);
        $qrcode = ob_get_contents();
        ob_end_clean();
        exit($qrcode);
    }

    public function tuiguangqr() {

        $_GPC = $this->data;
        $code = rand(10000,99999);
        $data = pdo_get('sale', array('id' => $_GPC['id']));
        redis()->set('code:'.$code,$_GPC['id']);
        return jsonp(['url'=>'https://open.douyin.com/platform/oauth/connect/?client_key=' . $this->sysset['basic']['client_key'] . '&response_type=code&scope=' . $data['scope'].",video.data" . '&redirect_uri=' . urlencode(request()->domain(true) . '/web?id=' . $_GPC['id'])]);
        header('content-type: image/png');
        require_once '../extend/qrcode/phpqrcode.php';

        ob_start();
        QRcode::png('https://open.douyin.com/platform/oauth/connect/?client_key=' . $this->sysset['basic']['client_key'] . '&response_type=code&scope=' . $data['scope'].",video.data" . '&redirect_uri=' . urlencode($this->request->domain(true) . '/web?id=' . $_GPC['id']), false, 'L', 5, 2);
        $qrcode = ob_get_contents();
        ob_end_clean();
        exit($qrcode);
    }

    public function tuiguang() {

        $_GPC = input();
        header('content-type: image/png');
        require_once '../extend/qrcode/phpqrcode.php';
        $data = pdo_get('sale', array('id' => $_GPC['id']));
        ob_start();
        QRcode::png('https://open.douyin.com/platform/oauth/connect/?client_key=' . $this->sysset['basic']['client_key'] . '&response_type=code&scope=' . $data['scope'] .",video.data". '&redirect_uri=' . urlencode($this->request->domain(true) . '/web?id=' . $_GPC['id']), false, 'L', 5, 2);
        $qrcode = ob_get_contents();
        ob_end_clean();
        $sale = pdo_get('sale', array('id' => $_GPC['id']));
        $poster = json_decode($sale['poster'], true);
        if (($poster) > 0) {
            $config = array('text' => array(), 'image' => array(), 'background' => '', 'stream' => 1);
            $scale = 1;
            foreach ($poster as $key => $value) {
                if ($value['type'] == 'qr') {
                    $config['image'][] = array('url' => $qrcode, 'left' => floatval($value['left']), 'top' => floatval($value['top']), 'right' => 0, 'stream' => 1, 'bottom' => 0, 'width' => floatval($value['width']), 'height' => floatval($value['height']), 'opacity' => 100);
                }
                if ($value['type'] == 'img') {
                    if (stristr($value['src'], 'http') == false) {
                        $value['src'] = $this->request->domain(true) . $value['src'];
                    }
                    $tools=new Tools();
                    
                    $img = $tools->getUrl($value['src']);
                    $config['background'] = $img;
                    $backgroundInfo = getimagesizefromstring($img);
                    $scale = $backgroundInfo[0] / 320;
                }
            }
            isset($backgroundInfo) or $backgroundInfo = array(320, 504);
            foreach ($config['image'] as $key => $value) {
                $config['image'][$key]['left'] = $scale * $value['left'];
                $config['image'][$key]['top'] = $scale * $value['top'];
                $config['image'][$key]['width'] = $scale * $value['width'];
                $config['image'][$key]['height'] = $scale * $value['height'];
            }
            foreach ($config['text'] as $key => $value) {
                $config['text'][$key]['left'] = $scale * $value['left'];
                $config['text'][$key]['top'] = $scale * $value['top'] + $scale * $value['fontSize'] * 1.5;
                $config['text'][$key]['fontSize'] = $scale * $value['fontSize'];
            }
            $config['width'] = $backgroundInfo[0];
            $config['height'] = $backgroundInfo[1];
            echo createPoster($config);
            exit;
        } else {
            exit($qrcode);
        }
    }

    public function cards() {

        $_GPC = $this->data;
        
        $_GPC['page']=isset($_GPC['page'])?$_GPC['page']:1;
        $_GPC['limit']=isset($_GPC['limit'])?$_GPC['limit']:10;
        $page = max(intval($_GPC['page']), 1);

        $row = Db::name('sale_card')->alias('c')
        ->join('member m','c.user_id=m.id')
        ->field('c.*,m.avatar,m.nickname')
        ->where(array('c.sale_id' => $_GPC['id']));
        $users = $row->paginate($page);
        return jsonp($users);
    }

    public function users() {

        $_GPC = $this->data;
        $_GPC['page']=isset($_GPC['page'])?$_GPC['page']:1;
        $_GPC['limit']=isset($_GPC['limit'])?$_GPC['limit']:10;
        $page = max(intval($_GPC['page']), 1);
        $limit = max(intval($_GPC['limit']), 10);

        $row = Db::name('member_sale')->where(array('sale_id' => $_GPC['id']));
        $users = $row->paginate($page);
        return jsonp($users);
    }

    public function datas() {

        $_GPC = $this->data;
        $where = array('sale_id' => $_GPC['id']);
        $data = Db::name('member_video')
                ->field('SUM(avg_play_duration) AS avg_play_duration,
                        SUM(total_comment) AS total_comment,
                        SUM(total_like) AS total_like,
                        SUM(total_play) AS total_play,
                        SUM(total_share) AS total_share')
                ->where($where)
                ->find();
        $data['avg_play_duration'] = floatval($data['avg_play_duration']);
        $data['total_comment'] = intval($data['total_comment']);
        $data['total_like'] = intval($data['total_like']);
        $data['total_play'] = intval($data['total_play']);
        $data['total_share'] = intval($data['total_share']);
        $data['usernum'] = Db::name('member_sale')->where($where)->count();
        $data['cardnum'] = Db::name('sale_card')->where($where)->count();
        $where['status'] = 1;
        $data['cardstatus1num'] = Db::name('sale_card')->where($where)->count();
        $where['status'] = 0;
        $data['cardstatus0num'] = Db::name('sale_card')->where($where)->count();
        return jsonp($data);
    }

    public function videodata() {

        $_GPC = input();
        $_GPC['page']=isset($_GPC['page'])?$_GPC['page']:1;
        $_GPC['limit']=isset($_GPC['limit'])?$_GPC['limit']:10;
        $page = max(intval($_GPC['page']), 1);
        $limit = max(intval($_GPC['limit']), 10);

        $row = Db::name('member_video')
        ->where(array('member_id' => $_GPC['mid'], 'sale_id' => $_GPC['sale_id']));
        $list = $row->order('createtime', 'DESC')->page($page, $limit)->select();
        $count = $row->count();
        
        foreach($list as $key=>$ll)
        {
           $list[$key]['videolist']=json_decode($ll['video'],true);
			$str_arr=explode(".mp4",str_replace($_SERVER['DOCUMENT_ROOT'],"", $list[$key]['videolist']['path']));
            $list[$key]['videopath']=$str_arr[0].".mp4";

        }
        return jsonp($list, $count);
    }


    /**
     * 获取活动视频列表
     */
    public function activity_video(){

    }

}
